<template>
  <div class="due-date-setter">
    <!-- 显示设置结果 -->
    <div class="result-display" @click="openDialog">
      <div class="result-content">
        <el-tag v-if="mode === 'relative'" type="primary" >
          相对时间: {{ relativeTimePreview }}
        </el-tag>
        <el-tag v-else-if="mode === 'absolute'" type="success" >
          绝对时间: {{ absoluteTimePreview || '未设置' }}
        </el-tag>
        <el-tag v-else-if="mode === 'expression'" type="warning" >
          表达式: {{ expressionValue ? `$\{${expressionValue}\}` : '未设置' }}
        </el-tag>
        <el-tag v-else type="info" >未设置</el-tag>
      </div>
      <el-button type="primary" link >
        <el-icon><Edit /></el-icon>
      </el-button>
    </div>

    <!-- 设置弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="截止时间设置"
      width="580px"
      :before-close="handleDialogClose"
      append-to-body
      class="due-date-dialog">
      <div class="due-date-dialog-content">
        <!-- 设置模式选择 -->
        <div class="mode-selector">
          <el-radio-group v-model="mode"  @change="handleModeChange">
            <el-radio-button label="relative">相对时间</el-radio-button>
            <el-radio-button label="absolute">绝对时间</el-radio-button>
            <el-radio-button label="expression">表达式</el-radio-button>
          </el-radio-group>
        </div>

        <!-- 相对时间设置 -->
        <div v-if="mode === 'relative'" class="relative-time-setting">
          <div class="time-input-group">
            <el-input-number
              v-model="relativeValue"
              :min="1"
              :max="999"
              style="width: 120px"
              @change="updateRelativeTime" />
            <el-select
              v-model="relativeUnit"
              style="width: 100px; margin-left: 8px"
              @change="updateRelativeTime">
              <el-option label="分钟" value="T" />
              <el-option label="小时" value="H" />
              <el-option label="天" value="D" />
              <el-option label="周" value="W" />
              <el-option label="月" value="M" />
              <el-option label="年" value="Y" />
            </el-select>
            <span class="time-suffix">后到期</span>
          </div>
          <div class="preview-text">
            生成格式：<code>{{ relativeTimePreview }}</code>
          </div>
        </div>

        <!-- 绝对时间设置 -->
        <div v-if="mode === 'absolute'" class="absolute-time-setting">
          <el-date-picker
            v-model="absoluteTime"
            type="datetime"
            placeholder="选择截止时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
            @change="updateAbsoluteTime"
            :clearable="false" />
          <div class="preview-text">
            生成格式：<code>{{ absoluteTimePreview }}</code>
          </div>
        </div>

        <!-- 表达式设置 -->
        <div v-if="mode === 'expression'" class="expression-setting">
          <el-input
            v-model="expressionValue"
            placeholder="输入表达式，如：${dueDate}"   
            @input="updateExpression">
            <template #prepend>
              <span>${</span>
            </template>
            <template #suffix>
              <span>}</span>
            </template>
          </el-input>
          <div class="expression-examples">
            <div class="examples-title">常用表达式示例：</div>
            <div class="example-items">
              <el-tag
                v-for="example in expressionExamples"
                :key="example.value"
                class="example-tag"
                @click="setExpressionExample(example.value)">
                {{ example.label }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 快速设置选项 -->
        <div v-if="mode === 'relative'" class="quick-options">
          <div class="quick-title">快速设置：</div>
          <div class="quick-buttons">
            <el-tag
              v-for="option in quickOptions"
              :key="option.label"
              class="example-tag"
              @click="setQuickOption(option)">
              {{ option.label }}
            </el-tag>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleDialogConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { 
  ElRadioGroup, 
  ElRadioButton, 
  ElInputNumber, 
  ElSelect, 
  ElOption, 
  ElDatePicker, 
  ElInput, 
  ElTag, 
  ElButton,
  ElDialog,
  ElIcon
} from 'element-plus'
import { Edit } from '@element-plus/icons-vue'

interface Props {
  modelValue?: string
}

interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: ''
})

const emit = defineEmits<Emits>()

// 设置模式：relative(相对时间) | absolute(绝对时间) | expression(表达式)
const mode = ref<'relative' | 'absolute' | 'expression'>('relative')

// 相对时间设置
const relativeValue = ref<number>(3)
const relativeUnit = ref<string>('D')

// 绝对时间设置
const absoluteTime = ref<string>('')

// 表达式设置
const expressionValue = ref<string>('dueDate')

// 弹窗可见性
const dialogVisible = ref(false)

// 临时存储值，用于取消时恢复
const tempValues = ref({
  mode: 'relative' as 'relative' | 'absolute' | 'expression',
  relativeValue: 3,
  relativeUnit: 'D',
  absoluteTime: '',
  expressionValue: 'dueDate'
})

// 快速设置选项
const quickOptions = [
  { label: '1小时后', value: 1, unit: 'H' },
  { label: '半天后', value: 12, unit: 'H' },
  { label: '1天后', value: 1, unit: 'D' },
  { label: '3天后', value: 3, unit: 'D' },
  { label: '1周后', value: 1, unit: 'W' },
  { label: '1月后', value: 1, unit: 'M' }
]

// 表达式示例
const expressionExamples = [
  { label: 'dueDate', value: 'dueDate' },
  { label: 'task.dueDate', value: 'task.dueDate' },
  { label: 'execution.dueDate', value: 'execution.dueDate' },
  { label: 'processInstance.dueDate', value: 'processInstance.dueDate' }
]

// 计算属性 - 相对时间预览
const relativeTimePreview = computed(() => {
  if (!relativeValue.value || !relativeUnit.value) return ''
  
  // ISO 8601期间格式：P[n]Y[n]M[n]DT[n]H[n]M[n]S
  // 时间部分（小时、分钟、秒）需要T前缀
  if (relativeUnit.value === 'T') {
    // 分钟需要在时间部分
    return `PT${relativeValue.value}M`
  } else if (relativeUnit.value === 'H') {
    // 小时需要在时间部分
    return `PT${relativeValue.value}H`
  } else {
    // 日期部分（年、月、日、周）
    return `P${relativeValue.value}${relativeUnit.value}`
  }
})

// 计算属性 - 绝对时间预览
const absoluteTimePreview = computed(() => {
  if (!absoluteTime.value) return ''
  return absoluteTime.value
})

// 初始化组件状态
const initializeComponent = () => {
  const value = props.modelValue

  if (!value) {
    // 默认为相对时间模式
    if (mode.value !== 'relative') {
      mode.value = 'relative'
    }
    return
  }

  // 检测是否为表达式
  if (value.startsWith('${') && value.endsWith('}')) {
    mode.value = 'expression'
    expressionValue.value = value.slice(2, -1)
    return
  }

  // 检测是否为ISO 8601期间格式 (P开头)
  if (value.startsWith('P')) {
    mode.value = 'relative'
    parseRelativeTime(value)
    return
  }

  // 检测是否为ISO 8601日期时间格式
  if (value.includes('T') || value.includes('-')) {
    mode.value = 'absolute'
    absoluteTime.value = value
    return
  }

  // 默认按表达式处理
  mode.value = 'expression'
  expressionValue.value = value
}

// 解析相对时间
const parseRelativeTime = (value: string) => {
  // 支持 P开头的日期部分：P1Y, P1M, P1D, P1W
  let match = value.match(/^P(\d+)([YMDW])$/)
  if (match) {
    relativeValue.value = parseInt(match[1])
    relativeUnit.value = match[2]
    return
  }
  
  // 支持 PT开头的时间部分：PT1H, PT30M
  match = value.match(/^PT(\d+)([HM])$/)
  if (match) {
    relativeValue.value = parseInt(match[1])
    if (match[2] === 'M') {
      relativeUnit.value = 'T' // 使用T代表分钟
    } else {
      relativeUnit.value = match[2] // H代表小时
    }
  }
}

// 更新相对时间
const updateRelativeTime = () => {
  const value = relativeTimePreview.value
  emit('update:modelValue', value)
  emit('change', value)
}

// 更新绝对时间
const updateAbsoluteTime = (value?: string) => {
  const timeValue = value || absoluteTime.value || ''
  absoluteTime.value = timeValue
  emit('update:modelValue', timeValue)
  emit('change', timeValue)
}

// 更新表达式
const updateExpression = () => {
  const value = expressionValue.value ? `\${${expressionValue.value}}` : ''
  emit('update:modelValue', value)
  emit('change', value)
}

// 模式切换处理
const handleModeChange = () => {
  // 延迟执行，确保DOM更新完成
  nextTick(() => {
    switch (mode.value) {
      case 'relative':
        // 确保相对时间有默认值
        if (!relativeValue.value) {
          relativeValue.value = 3
        }
        if (!relativeUnit.value) {
          relativeUnit.value = 'D'
        }
        updateRelativeTime()
        break
      case 'absolute':
        // 如果绝对时间为空，设置默认值为当前时间
        if (!absoluteTime.value) {
          const now = new Date()
          // 设置为当前时间+1小时作为默认截止时间
          now.setHours(now.getHours() + 1)
          absoluteTime.value = now.toISOString().slice(0, 19)
        }
        updateAbsoluteTime(absoluteTime.value)
        break
      case 'expression':
        // 确保表达式有默认值
        if (!expressionValue.value) {
          expressionValue.value = 'dueDate'
        }
        updateExpression()
        break
    }
  })
}

// 设置快速选项
const setQuickOption = (option: any) => {
  relativeValue.value = option.value
  relativeUnit.value = option.unit
  updateRelativeTime()
}

// 设置表达式示例
const setExpressionExample = (value: string) => {
  expressionValue.value = value
  updateExpression()
}

// 打开弹窗
const openDialog = () => {
  // 保存当前值用于取消时恢复
  tempValues.value = {
    mode: mode.value,
    relativeValue: relativeValue.value,
    relativeUnit: relativeUnit.value,
    absoluteTime: absoluteTime.value,
    expressionValue: expressionValue.value
  }
  dialogVisible.value = true
}

// 关闭弹窗
const handleDialogClose = () => {
  // 恢复到打开弹窗前的值
  mode.value = tempValues.value.mode
  relativeValue.value = tempValues.value.relativeValue
  relativeUnit.value = tempValues.value.relativeUnit
  absoluteTime.value = tempValues.value.absoluteTime
  expressionValue.value = tempValues.value.expressionValue
  dialogVisible.value = false
}

// 确认设置
const handleDialogConfirm = () => {
  // 根据当前模式更新值
  switch (mode.value) {
    case 'relative':
      updateRelativeTime()
      break
    case 'absolute':
      updateAbsoluteTime(absoluteTime.value)
      break
    case 'expression':
      updateExpression()
      break
  }
  dialogVisible.value = false
}

// 监听props变化
watch(() => props.modelValue, (newValue, oldValue) => {
  // 只有在值真正发生变化时才重新初始化
  if (newValue !== oldValue) {
    initializeComponent()
  }
}, { immediate: true })
</script>

<style scoped lang="scss">
// 设计令牌
$primary-color: #3b82f6;
$border-color: #e5e7eb;
$text-color: #1f2937;
$text-secondary: #6b7280;
$text-muted: #9ca3af;
$bg-light: #f9fafb;
$radius: 6px;
$spacing-xs: 4px;
$spacing-sm: 8px;
$spacing-md: 12px;
$spacing-lg: 16px;
$spacing-xl: 20px;

.due-date-setter {
  // 结果显示区域
  .result-display {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: $spacing-sm;
    background: #f8fafc;
    border-radius: $radius;
    border: 1px solid $border-color;
    cursor: pointer;
    transition: all 0.2s ease;
    
    &:hover {
      border-color: $primary-color;
      background: #f0f9ff;
      box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
    
    .result-content {
      flex: 1;
      
      .el-tag {
        margin-right: $spacing-sm;
      }
    }
  }
}

// 弹窗样式 - 使用全局样式确保生效
.due-date-dialog {
  .el-dialog__header {
    padding: 20px 20px 10px !important;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .el-dialog__body {
    padding: 20px !important;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px !important;
    border-top: 1px solid #f0f0f0;
  }
  
  // 确保弹窗内容有足够的内边距
  .due-date-dialog-content {
    padding: 10px;
  }
}

// 弹窗内容
.due-date-dialog-content {
  // 模式选择器
  .mode-selector {
    margin-bottom: $spacing-lg;
    
    :deep(.el-radio-group) {
      display: flex;
      width: 100%;
      border-radius: $radius;
      overflow: hidden;
      border: 1px solid $border-color;
      
      .el-radio-button {
        flex: 1;
        
        .el-radio-button__inner {
          width: 100%;
          border: none !important;
          border-right: 1px solid $border-color !important;
          border-radius: 0;
          padding: $spacing-sm $spacing-md;
          font-size: 13px;
          font-weight: 500;
          background: #fff;
          color: $text-secondary;
          transition: all 0.2s ease;
          
          &:hover {
            background: $bg-light;
            color: $primary-color;
          }
        }
        
        &:last-child .el-radio-button__inner {
          border-right: none !important;
        }
        
        &.is-active .el-radio-button__inner {
          background: $primary-color !important;
          color: #fff !important;
          box-shadow: inset 0 0 0 1px $primary-color;
        }
      }
    }
  }

  // 相对时间设置
  .relative-time-setting {
    margin-bottom: $spacing-lg;
    padding: $spacing-md;
    background: #fff;
    border-radius: $radius;
    border: 1px solid rgba(226, 232, 240, 0.6);
    
    .time-input-group {
      display: flex;
      align-items: center;
      gap: $spacing-md;
      margin-bottom: $spacing-md;
      padding: $spacing-md $spacing-lg;
      background: #f8fafc;
      border-radius: $radius;
      border: 1px solid rgba(226, 232, 240, 0.3);
      
      :deep(.el-input-number) {
        flex: 1;
        
        .el-input__wrapper {
          border-radius: 4px;
          border: 1px solid $border-color;
          background: #fff;
          
          &:hover {
            border-color: $primary-color;
          }
          
          &.is-focus {
            border-color: $primary-color;
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
          }
        }
      }
      
      :deep(.el-select) {
        flex: 1;
        
        .el-select__wrapper {
          border-radius: 4px;
          border: 1px solid $border-color;
          background: #fff;
          
          &:hover {
            border-color: $primary-color;
          }
          
          &.is-focus {
            border-color: $primary-color;
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
          }
        }
      }
      
      .time-suffix {
        font-size: 13px;
        color: $text-secondary;
        font-weight: 500;
        white-space: nowrap;
        margin-left: $spacing-sm;
      }
    }
  }

  // 绝对时间设置
  .absolute-time-setting {
    margin-bottom: $spacing-lg;
    padding: $spacing-md;
    background: #fff;
    border-radius: $radius;
    border: 1px solid rgba(226, 232, 240, 0.6);
    
    :deep(.el-date-editor) {
      width: 100%;
    }
  }

  // 表达式设置
  .expression-setting {
    margin-bottom: $spacing-lg;
    padding: $spacing-md;
    background: #fff;
    border-radius: $radius;
    border: 1px solid rgba(226, 232, 240, 0.6);
    
    :deep(.el-input-group__prepend),
    :deep(.el-input-group__append) {
      background: $bg-light;
      border-color: $border-color;
      color: $text-secondary;
      font-weight: 500;
      padding: 0 $spacing-sm;
    }
    
    .expression-examples {
      margin-top: $spacing-md;
      padding-top: $spacing-md;
      border-top: 1px solid #f0f0f0;
      
      .examples-title {
        font-size: 12px;
        color: $text-secondary;
        margin-bottom: $spacing-sm;
        font-weight: 600;
      }
      
      .example-items {
        display: flex;
        flex-wrap: wrap;
        gap: $spacing-sm;
        
        .example-tag {
          cursor: pointer;
          transition: all 0.2s ease;
          border-radius: 4px;
          font-size: 11px;
          padding: 6px $spacing-sm;
          
          &:hover {
            background: $primary-color;
            color: white;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
          }
        }
      }
    }
  }

  // 预览文本
  .preview-text {
    margin-top: $spacing-md;
    padding: $spacing-lg;
    background: rgba(59, 130, 246, 0.04);
    border-radius: $radius;
    border-left: 3px solid $primary-color;
    
    font-size: 12px;
    color: $text-secondary;
    line-height: 1.5;
    
    code {
      background: #fff;
      padding: 6px 10px;
      border-radius: 4px;
      font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
      color: $primary-color;
      font-weight: 600;
      margin-left: 4px;
      border: 1px solid rgba(59, 130, 246, 0.2);
      display: inline-block;
      min-width: 120px;
      text-align: center;
    }
  }

  // 快速选项
  .quick-options {
    margin-top: $spacing-lg;
    padding: $spacing-md;
    background: #fff;
    border-radius: $radius;
    border: 1px solid rgba(226, 232, 240, 0.6);
    
    .quick-title {
      font-size: 12px;
      color: $text-secondary;
      margin-bottom: $spacing-sm;
      font-weight: 600;
    }
    
    .quick-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: $spacing-sm;
      
      :deep(.example-tag) {
        cursor: pointer;
        transition: all 0.2s ease;
        border-radius: 4px;
        font-size: 11px;
        padding: 6px $spacing-sm;
        background: #fff;
        color: $text-secondary;
        border: 1px solid $border-color;
        
        &:hover {
          background: $primary-color;
          color: white;
          border-color: $primary-color;
          transform: translateY(-1px);
          box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
        }
      }
    }
  }
}

// 弹窗底部
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: $spacing-sm;
  padding: $spacing-sm 0;
}

// Element Plus 组件样式优化
:deep(.el-input-number) {
  .el-input__wrapper {
    border-radius: 4px;
    border: 1px solid $border-color;
    background: #fff;
    
    &:hover {
      border-color: $primary-color;
    }
    
    &.is-focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
  }
}

:deep(.el-select) {
  .el-select__wrapper {
    border-radius: 4px;
    border: 1px solid $border-color;
    background: #fff;
    
    &:hover {
      border-color: $primary-color;
    }
    
    &.is-focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
  }
}

:deep(.el-date-picker) {
  width: 100%;
  
  .el-input__wrapper {
    border-radius: 4px;
    border: 1px solid $border-color;
    background: #fff;
    
    &:hover {
      border-color: $primary-color;
    }
    
    &.is-focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    border-radius: 4px;
    border: 1px solid $border-color;
    background: #fff;
    
    &:hover {
      border-color: $primary-color;
    }
    
    &.is-focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
  }
  
  .el-input-group__prepend,
  .el-input-group__append {
    background: $bg-light;
    border-color: $border-color;
    color: $text-secondary;
    font-weight: 500;
    padding: 0 $spacing-sm;
  }
}
</style>